<template>
  <!-- 客户端 -->
  <div class="home" style="height: 100%; width: 100%">
    <div class="order">
      <div class="item">
        <div class="flex-box">
          购买数量
          <span>222</span>
        </div>
        <div class="flex-box">
          <span />
          <span @click="handleOk" class="button"
            >我已支付<span>
              <vueCountdownPlus
                ref="vueCountdownPlus"
                @finish="handleFinish"
                :time="15 * 60 * 1000"
                format="mm:ss" /></span
          ></span>
        </div>
      </div>
      <div class="quicks">
        <h2>请选择您的支付方式</h2>
        <p
          @click="sendQuickQs(item)"
          v-for="(item, index) in quickList"
          :key="item.iid"
        >
          {{ index + 1 }}.{{ item.text }}
        </p>
      </div>
    </div>

    <div class="chat-content">
      <JwChat
        style="height: 100%; width: 100%"
        width="100%"
        :taleList="list"
        :scrollType="'scroll'"
        @enter="bindEnter"
        @clickTalk="talkEvent"
        v-model="inputMsg"
        :toolConfig="tool"
      >
        <template slot="tools">
          <input
            @change="referenceUpload"
            type="file"
            id="common_chat_opr_fileUpload"
            style="display: none"
          />
          <!-- <div
          style="width: 20rem; text-align: right"
          @click="toolEvent('自定义')"
        > -->
          <!-- <el-upload
            class="upload-demo"
            ref="uploadDemo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-success="handleAvatarSuccess"
          >
          </el-upload> -->
          <!-- <b slot="tools">插槽</b> -->
          <!-- <JwChat-icon type="icon-lishi" title="自定义" /> -->
          <!-- </div> -->
        </template>
      </JwChat>
      <!-- <Toast ref="Toast" /> -->
    </div>
  </div>
</template>

<script>
import { uploadImg } from "@/utils/uploadImg";
import moment from "moment";
import axios from "axios";
import vueCountdownPlus from "vue-countdown-plus";
export default {
  components: { vueCountdownPlus },
  data() {
    return {
      currentData: {},
      endTime: moment(),
      quickList: [
        {
          text: "加微信好友支付",
          id: "wx",
        },
        {
          text: "加支付宝好友支付",
          id: "alipay",
        },
      ],
      inputMsg: "",
      list: [],
      tool: {
        show: ["img", ["文件1", "", "美图"]], // 二级数组中放自定义名称
        callback: this.toolEvent,
      },
    };
  },
  created() {},

  methods: {
    handleOk() {
      this.$refs.vueCountdownPlus.stop();
      this.$message.success("已通知客服，请耐心等待");
    },
    handleFinish() {
      const currentData = JSON.parse(localStorage.getItem("currentData"));
      if (!currentData) {
        this.$message.warning("通话已结束");
        return false;
      }
      // 发送的数据
      const postData = {
        to: currentData["to"],
        from: this.$route.query.id,
        text: "",
        type: "3",
      };
      this.WS.send(postData);
    },

    sendQuickQs(item) {
      const currentData = JSON.parse(localStorage.getItem("currentData"));
      const msgObj = {
        date: moment().format("YYYY-MM-DD HH:mm:ss"),
        text: { text: item.text },
        mine: true,
        name: "用户" + currentData.from,
        img: require("@/assets/user.png"),
      };
      if (!currentData) {
        this.$message.warning("通话已结束");
        return false;
      }
      // 发送的数据
      const postData = {
        to: currentData["to"],
        from: this.$route.query.id,
        text: item.text,
        type: "0",
      };
      this.WS.send(postData);
      this.list.push(msgObj);
    },
    getHistory() {
      axios({
        url: "http://116.62.168.208:8183/chat/list",
        params: {
          pageIndex: 1,
          pageSize: 10000,
          cRecordId: this.$route.query.id,
        },
      }).then(({ data }) => {
        if (!data.code) {
          const detail = data.data.detail;
          const conversionData = detail.map((item) => {
            let msgObj = {};
            console.log(item);
            if (item.cType == 1) {
              // 图片
              msgObj = {
                date: moment(Number(item.cDate)).format("YYYY-MM-DD HH:mm:ss"),
                text: { text: "<img data-src='" + item.cTxt + "'/>" },
                mine: item.cTo != this.$route.query.id,
                name:
                  item.cTo == this.$route.query.id
                    ? "客服"
                    : "用户" + item.cFrom,
                img:
                  item.cTo != this.$route.query.id
                    ? require("@/assets/service.png")
                    : require("@/assets/user.png"),
              };
            } else {
              msgObj = {
                date: moment(Number(item.cDate)).format("YYYY-MM-DD HH:mm:ss"),
                text: { text: item.cTxt },
                mine: item.cTo != this.$route.query.id,
                name:
                  item.cTo == this.$route.query.id
                    ? "客服"
                    : "用户" + item.cFrom,
                img:
                  item.cTo == this.$route.query.id
                    ? require("@/assets/service.png")
                    : require("@/assets/user.png"),
              };
            }

            return msgObj;
          });
          console.log(conversionData);
          // let list = conversionData.concat(this.taleList);
          let list = conversionData.concat(this.list);
          this.list = list;
        }
      });
    },
    referenceUpload(e) {
      console.log(e.target.files[0]);
      // 2.文件上传
      let formData = new FormData();
      formData.append("file", e.target.files[0]);
      formData.append("fileType", "images");
      uploadImg(formData).then(({ data }) => {
        let img = data.data;
        const msgObj = {
          date: "2020/05/20 23:19:07",
          text: { text: "<img data-src='" + img + "'/>" },
          mine: true,
          name: "姚二傻",
          img: require("@/assets/user.png"),
        };
        const currentData = JSON.parse(localStorage.getItem("currentData"));
        if (!currentData) {
          this.$message.warning("通话已结束");
          return false;
        }
        // 发送的数据
        const postData = {
          to: currentData["to"],
          from: this.$route.query.id,
          text: img,
          type: "1",
        };
        document.getElementById("common_chat_opr_fileUpload").value = "";

        this.WS.send(postData);
        this.list.push(msgObj);
      });
    },
    init() {
      console.log(this.$route.query.id);
      let id = this.$route.query.id || "111";
      this.WS = new this.$WSocket({
        url: `ws://116.62.168.208:8183/webSocket/${id}/-1/user`,
        // 心跳时间（单位:ms）
        // 'heartBeat':5000,
        // 发送心跳信息（支持json传入）(这个一般内容不重要，除非后端变态)
        // 'heartMsg':'hello',
        // 开起重连
        reconnect: false,
        // 重连间隔时间（单位:ms）
        // 'reconnectTime':5000,
        // 重连次数
        // 'reconnectTimes':10
      });
      this.WS.onerror((e) => {
        console.log(e, "链接失败");
      });
      this.WS.onmessage((data) => {
        if (!this.first) {
          this.getHistory();
          this.first = true;
          localStorage.setItem("currentData", data);
        }
        this.updateList(JSON.parse(data));
      });
      this.WS.onopen((e) => {
        console.log(e);
      });
    },
    updateList(data) {
      if (data.type == 1) {
        this.list.push({
          date: data.date,
          text: { text: "<img data-src='" + data.text + "'/>" },
          mine: false,
          name: "客服",
          img: require("@/assets/service.png"),
        });
      } else {
        this.list.push({
          date: data.date,
          text: { text: data.text },
          mine: false,
          name: "客服",
          img: require("@/assets/service.png"),
        });
      }
    },
    bindEnter(e) {
      console.log(e);
      const msg = this.inputMsg;
      if (!msg) return;
      // 展示的数据格式
      const msgObj = {
        date: moment().format("YYYY-MM-DD HH:mm:ss"),
        text: { text: msg },
        mine: true,
        name: "姚二傻",
        img: require("@/assets/user.png"),
      };
      const currentData = JSON.parse(localStorage.getItem("currentData"));
      if (!currentData) {
        this.$message.warning("通话已结束");
        return false;
      }
      // 发送的数据
      const postData = {
        to: currentData["to"],
        from: this.$route.query.id,
        text: msg,
        type: "0",
      };
      this.WS.send(postData);
      this.list.push(msgObj);
    },
    toolEvent(type, obj) {
      console.log("tools", type, obj);
      document.querySelector("#common_chat_opr_fileUpload").click();
      // this.$refs.uploadDemo.children[0].$refs.input.click();
      // document.querySelector('.el-upload__input').click
      // console.log(this.$refs.uploadDemo);
    },
    talkEvent(play) {
      console.log(play);
    },
  },
  mounted() {
    this.init();

    // const img = "https://www.baidu.com/img/flexible/logo/pc/result.png";
    // const list = [
    //   {
    //     date: "2020/04/25 21:19:07",
    //     text: { text: "起床不" },
    //     mine: false,
    //     name: "留恋人间不羡仙",
    //     img: "/image/one.jpeg",
    //   },
    //   {
    //     date: "2020/04/25 21:19:07",
    //     text: {
    //       text: "<audio data-src='https://www.w3school.com.cn/i/horse.mp3'/>",
    //     },
    //     mine: false,
    //     name: "只盼流星不盼雨",
    //     img: "/image/two.jpeg",
    //   },
    //   {
    //     date: "2020/04/25 21:19:07",
    //     text: { text: "<img data-src='" + img + "'/>" },
    //     mine: false,
    //     name: "只盼流星不盼雨",
    //     img: "/image/two.jpeg",
    //   },
    //   {
    //     date: "2020/04/25 21:19:07",
    //     text: { text: "<img data-src='/image/three.jpeg'/>" },
    //     mine: false,
    //     name: "只盼流星不盼雨",
    //     img: "/image/two.jpeg",
    //   },
    //   {
    //     date: "2020/04/16 21:19:07",
    //     text: {
    //       text: "<video data-src='https://www.w3school.com.cn/i/movie.mp4' controls='controls' />",
    //     },
    //     mine: true,
    //     name: "JwChat",
    //     img: "/image/three.jpeg",
    //   },
    //   {
    //     date: "2021/03/02 13:14:21",
    //     mine: false,
    //     name: "留恋人间不羡仙",
    //     img: "/image/one.jpeg",
    //     text: {
    //       system: {
    //         title: "在接入人工前，智能助手将为您首次应答。",
    //         subtitle: "猜您想问:",
    //         content: [
    //           {
    //             id: `system1`,
    //             text: "组件如何使用",
    //           },
    //           {
    //             id: `system2`,
    //             text: "组件参数在哪里查看",
    //           },
    //           {
    //             id: "system",
    //             text: "我可不可把组件用在商业",
    //           },
    //         ],
    //       },
    //     },
    //   },
    //   {
    //     date: "2020/04/25 21:19:07",
    //     text: {
    //       text: "<i class='el-icon-document-checked' style='font-size:2rem;'/>",
    //       subLink: {
    //         text: "a.txt",
    //         prop: {
    //           underline: false,
    //         },
    //       },
    //     },
    //     mine: false,
    //     name: "留恋人间不羡仙",
    //     img: "../image/one.jpeg",
    //   },
    // ];
    // this.list = list;
  },
};
</script>
<style lang="less" scoped>
/deep/ .chatPage .taleBox {
  display: flex;
}
/deep/.wrapper {
  flex: 1;
  height: auto !important;
  // width: 100% !important;
  // height: calc(100vh - 330px) !important;
}
/deep/ .chatPage .taleBox {
  // height: calc(100% - 140px - 184px) !important;
}

.home {
  /deep/.toolsBox {
    background: #2a3142;
  }
  /deep/.wrapper .web__main .web__main-user cite {
    color: #fff;
  }
  .chatPage {
    background: none;
  }
  /deep/.wrapper .web__main .web__main-text {
    background: #373e4e;
    border-color: #373e4e;
    color: #fff;
  }
  /deep/.wrapper .web__main .web__main-arrow:after {
    border-right-color: #373e4e;
  }
  /deep/.el-link.el-link--default {
    color: #fff;
  }
  /deep/.web__msg-input {
    background: transparent;
    color: #fff;
  }
  // display: flex;
  // flex-flow: column;
  background: #1b202d;
  padding-top: 183px;
  box-sizing: border-box;

  .order {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    .quicks {
      h2 {
        padding: 0px 16px;
        margin: 0;
        color: #fff;
        // font-size: px;
      }
      p {
        margin: 0;
        text-align: left;
        color: #2966e0;
        text-decoration: underline;
        cursor: pointer;
        padding: 6px 16px;
      }
    }
    div.item {
      /* core/pink */

      /* core/mint */

      background: #252e36;
      /* shadow/level 3 */

      box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.12),
        0px 16px 32px rgba(0, 0, 0, 0.08);
      color: #fff;
      margin: 0px;
      padding: 10px;
      span.button {
        background: orange;
        border-radius: 4px;
        display: inline-block;
        min-width: 100px;
        line-height: 34px;
        padding: 0 10px;
        height: 34px;
        span {
          margin-left: 6px;
        }
      }
    }
  }
  .chat-content {
    // flex: 1;
    height: 100%;
  }
}
.flex-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  line-height: 24px;
  font-weight: bold;
}
</style>
